const socket = io();
const userId = localStorage.getItem('userId');
const currentNickname = localStorage.getItem('nickname');
if (!userId) {
  console.error('用户未登录，无法加载聊天界面');
  window.location.href = 'index.html'; // 重定向到登录页
} else {
  // 发送上线事件,让服务器将 socket 加入对应房间
  socket.emit('online', {
    userId: userId,
    nickname: currentNickname
  });
}

const nickname = localStorage.getItem('nickname');

const avatarUrl = localStorage.getItem('avatar') || 'upload/images/default_head.jpg';

// 渲染昵称
document.getElementById('nickname').textContent = nickname || '无名英雄';
document.title = document.getElementById('nickname').textContent = nickname || '无名英雄';

// 渲染头像
const avatarEl = document.getElementById('avatar');
avatarEl.src = avatarUrl;
avatarEl.alt = nickname || '头像';

// ===== 面板切换逻辑 =====
const btnFriends = document.getElementById('btn-friends');
const btnAdd     = document.getElementById('btn-add');
const panelF    = document.getElementById('panel-friends');
const panelA    = document.getElementById('panel-add');

function showFriendsPanel() {
  panelF.style.display = '';
  panelA.style.display = 'none';
  btnFriends.classList.add('active');
  btnAdd.classList.remove('active');
}

function showAddPanel() {
  panelF.style.display = 'none';
  panelA.style.display = '';
  btnAdd.classList.add('active');
  btnFriends.classList.remove('active');
}

// 初次加载默认展示好友列表
showFriendsPanel();

btnFriends.addEventListener('click', showFriendsPanel);
btnAdd.addEventListener('click', showAddPanel);
// ===== 切换逻辑结束 =====

socket.emit('getFriends', userId);

let friendList = []; // 添加全局变量
socket.on('friendList', async (friends) => {
  friendList = friends;
  const listEl = document.getElementById('friendList');
  listEl.innerHTML = '';

  for (const friend of friends) {
    const isOnline = await new Promise((resolve) => {
      socket.emit('isOnline', friend.userId, resolve);
    });

    // 获取最后一条消息
    let lastMessage = null;
    try {
      const response = await axios.get(`/api/chat/last-message`, {
        params: {
          userA: userId,
          userB: friend.userId
        }
      });
      lastMessage = response.data;
      if (lastMessage && lastMessage.content && lastMessage.content.length > 5) {
        // 取前五个字符+...
        lastMessage.content = lastMessage.content.slice(0, 5) + '...';
      }
    } catch (err) {
      console.error('获取最后一条消息失败:', err);
    }

    // 构建列表项
    const li = document.createElement('li');
    li.classList.add('friend-item');

    // 卡片容器
    const card = document.createElement('div');
    card.classList.add('friend-card');
    card.setAttribute('data-friend-id', friend.userId);

    // 左侧信息区
    const infoDiv = document.createElement('div');
    infoDiv.classList.add('friend-info');

    // 头像
    const avatar = document.createElement('div');
    avatar.classList.add('friend-avatar');
    avatar.innerHTML = `<img src="${friend.avatar}" alt="头像">`;
    
    // 为头像添加点击事件（显示资料）
    const avatarImg = avatar.querySelector('img');
    avatarImg.addEventListener('click', async (e) => {
      e.preventDefault();
      e.stopPropagation();
      try {
        const response = await axios.get(`/api/user/profile/${friend.userId}`);
        const friendData = response.data;
        
        // 更新模态框中的信息
        document.getElementById('modalFriendAvatar').src = friendData.avatar || 'upload/images/default_head.jpg';
        document.getElementById('modalFriendId').textContent = friendData.userId;
        document.getElementById('modalFriendNickname').textContent = friendData.nickname;
        document.getElementById('modalFriendEmail').textContent = friendData.email;
        document.getElementById('modalFriendGender').textContent = friendData.gender || '未设置';
        document.getElementById('modalFriendBio').textContent = friendData.bio || '这个人很懒，什么都没写~';
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('friendProfileModal'));
        modal.show();
      } catch (error) {
        console.error('获取好友资料失败:', error);
        alert('获取好友资料失败，请稍后重试');
      }
    });

    // 昵称和在线状态
    const name = document.createElement('div');
    name.classList.add('friend-name');
    const remark = (await axios.get(`/api/friend/get-remark`, {
      params: { userId, friendId: friend.userId }
    })).data.remark;
    name.textContent = remark || friend.nickname;
    const statusDot = document.createElement('span');
    statusDot.className = 'friend-status ' + (isOnline ? 'online' : 'offline');
    name.appendChild(statusDot);

    infoDiv.append(avatar, name);

    // 右侧消息区
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('friend-message');

    if (lastMessage) {
      const content = document.createElement('div');
      content.classList.add('last-message');
      content.textContent = lastMessage.content;

      const time = document.createElement('div');
      time.classList.add('message-time');
      time.textContent = new Date(lastMessage.timestamp).toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit'
      });

      messageDiv.append(content, time);
    }

    // 组装卡片
    card.append(infoDiv, messageDiv);
    li.appendChild(card);
    listEl.appendChild(li);

    // 卡片点击事件（进入聊天）
    card.onclick = async (e) => {
      // 如果点击的是头像，不进行跳转
      if (e.target.tagName.toLowerCase() === 'img') {
        return;
      }
      
      localStorage.setItem('chatFriendId', friend.userId);
      localStorage.setItem('chatFriendNickname', name.textContent);
      localStorage.setItem('chatFriendAvatar', friend.avatar);

      // 标记消息为已读
      try {
        await axios.put('/api/chat/read', {
          senderId: friend.userId,
          receiverId: userId
        });
        unreadCounts[friend.userId] = 0;
        updateUnreadBadge(friend.userId, 0);
      } catch (err) {
        console.error('标记已读失败:', err);
      }
      
      window.location.href = 'chatroom.html';
    };
  }

  // 在好友列表渲染完成后初始化未读消息
  await initializeUnreadCounts();

  // 初始化卡片倾斜效果
  VanillaTilt.init(document.querySelectorAll('.friend-card'), {
    max: 15,
    speed: 400,
    glare: true,
    'max-glare': 0.2
  });
});

document.getElementById('logoutButton').addEventListener('click', () => {
  localStorage.removeItem('userId');
  localStorage.removeItem('nickname');
  localStorage.removeItem('chatFriendId');
  window.location.href = 'index.html';
});

document.getElementById('addFriendButton').addEventListener('click', () => {
  const friendId = document.getElementById('addFriendInput').value.trim();
  if (!friendId) return;
  socket.emit('addFriend', { userId, friendId });
});


socket.on('friendOnline', ({ userId }) => {
  // 找到对应的好友项并更新状态
  const card = document.querySelector(`.friend-card[data-friend-id="${userId}"]`);
  if (card) {
    const statusDot = card.querySelector('.friend-status');
    if (statusDot) {
      statusDot.classList.remove('offline');
      statusDot.classList.add('online');
    }
  }
});

socket.on('friendOffline', ({ userId }) => {
  // 找到对应的好友项并更新状态
  const card = document.querySelector(`.friend-card[data-friend-id="${userId}"]`);
  if (card) {
    const statusDot = card.querySelector('.friend-status');
    if (statusDot) {
      statusDot.classList.remove('online');
      statusDot.classList.add('offline');
    }
  }
});

socket.on('addFriendResult', (result) => {
  const msgEl = document.getElementById('addFriendMessage');
  msgEl.textContent = result.success
    ? `已成功添加好友 ${result.friendId}`
    : result.message || '添加失败';
  msgEl.classList.toggle('success', result.success);
  msgEl.classList.toggle('error', !result.success);

  if (result.success) {
    // 微动效：按钮闪烁
    anime({
      targets: '#addFriendButton',
      scale: [1.0, 1.05, 1.0],
      duration: 400,
      easing: 'easeInOutSine'
    });
    socket.emit('getFriends', userId);
  }
});

const weatherLayer = document.getElementById('weatherLayer');
const weatherButtons = document.querySelectorAll('.weather-toggle button');

weatherButtons.forEach(btn => {
  btn.addEventListener('click', () => {
    const type = btn.dataset.weather;
    setWeatherEffect(type);
  });
});

function setWeatherEffect(type) {
  weatherLayer.innerHTML = '';
  clearInterval(window._weatherInterval);

  if (type === 'snow') {
    window._weatherInterval = setInterval(() => {
      const el = document.createElement('div');
      el.textContent = '❄';
      el.style.cssText = `
        position: absolute;
        top: -20px;
        left: ${Math.random() * 100}vw;
        font-size: ${8 + Math.random() * 16}px;
        color: #fff;
        opacity: ${0.4 + Math.random() * 0.6};
        animation: fallSnow 6s linear forwards;
      `;
      weatherLayer.appendChild(el);
      el.addEventListener('animationend', () => el.remove());
    }, 200);
  }

  else if (type === 'rain') {
    window._weatherInterval = setInterval(() => {
      const drop = document.createElement('div');
      drop.style.cssText = `
        position: absolute;
        top: -20px;
        left: ${Math.random() * 100}vw;
        width: 2px;
        height: ${10 + Math.random() * 20}px;
        background: #76eefa;
        opacity: 0.5;
        animation: fallRain 2s linear forwards;
      `;
      weatherLayer.appendChild(drop);
      drop.addEventListener('animationend', () => drop.remove());
    }, 100);
  }

  else if (type === 'cloud') {
    window._weatherInterval = setInterval(() => {
      const cloud = document.createElement('div');
      cloud.textContent = '☁';
      cloud.style.cssText = `
        position: absolute;
        top: ${100 + Math.random() * 100 % 73}px;
        right: 100px;
        font-size: 80px;
        color: #fff;
        opacity: 0.8;
        animation: driftCloud ${ Math.max(6, Math.random() * 100 % 15) }s linear infinite;
      `;
      weatherLayer.appendChild(cloud);
      drop.addEventListener('animationend', () => cloud.remove());
    }, 3000);
  }

  else if (type === 'suncloud') {
    const sun = document.createElement('div');
    sun.textContent = '☀';
    sun.style.cssText = `
      position: absolute;
      top: 100px;
      right: 100px;
      font-size: 80px;
      color: #ffdd57;
      animation: pulseSun 3s ease-in-out infinite;
    `;
    const cloud = document.createElement('div');
    cloud.textContent = '☁';
    cloud.style.cssText = `
      position: absolute;
      top: 100px;
      right: 100px;
      font-size: 80px;
      color: #fff;
      opacity: 0.8;
      animation: driftCloud 15s linear infinite;
    `;
    weatherLayer.append(sun, cloud);
    window._weatherInterval = setInterval(() => {
      const cloud = document.createElement('div');
      cloud.textContent = '☁';
      cloud.style.cssText = `
        position: absolute;
        top: ${100 + Math.random() * 100 % 73}px;
        right: 100px;
        font-size: 80px;
        color: #fff;
        opacity: 0.8;
        animation: driftCloud ${ Math.max(6, Math.random() * 100 % 15) }s linear infinite;
      `;
      weatherLayer.appendChild(cloud);
      drop.addEventListener('animationend', () => cloud.remove());
    }, 3000);
  }
}

const unreadCounts = {};

// 初始化时获取所有未读消息数
async function initializeUnreadCounts() {
  try {
    const response = await axios.get(`/api/chat/unread/${userId}`);
    response.data.forEach(item => {
      unreadCounts[item._id] = item.count;
      updateUnreadBadge(item._id, item.count);
    });
  } catch (err) {
    console.error('获取未读消息数失败:', err);
  }
}

// 更新未读消息徽章
function updateUnreadBadge(friendId, count) {
  console.log("正在更新未读消息徽章:", {friendId, count});
  const friendCard = document.querySelector(`[data-friend-id="${friendId}"]`);
  console.log("找到的好友卡片:", friendCard);
  
  if (!friendCard) {
    console.warn(`未找到好友卡片: ${friendId}`);
    return;
  }
  
  let badge = friendCard.querySelector('.unread-badge');
  console.log("当前徽章元素:", badge);
  
  if (count > 0) {
    if (!badge) {
      badge = document.createElement('div');
      badge.className = 'unread-badge';
      const avatarEl = friendCard.querySelector('.friend-avatar');
      if (avatarEl) {
        avatarEl.appendChild(badge);
      } else {
        console.error('未找到头像容器');
        return;
      }
    }
    badge.textContent = count;
    console.log(`已更新徽章数字为: ${count}`);
  } else if (badge) {
    badge.remove();
    console.log('已移除徽章');
  }
}

// 监听新消息通知
socket.on('newMessageNotice', async (data) => {
  const senderId = data.from;
  const sender = friendList.find(f => f.userId === senderId);
  if (!sender) {
    console.warn(`未找到发送者信息: ${senderId}`);
    return;
  }

  // 获取最新的消息内容
  try {
    const response = await axios.get(`/api/chat/last-message`, {
      params: {
        userA: userId,
        userB: senderId
      }
    });
    
    const lastMessage = response.data;
    if (lastMessage) {
      // 更新消息显示
      const friendCard = document.querySelector(`[data-friend-id="${senderId}"]`);
      if (friendCard) {
        let messageDiv = friendCard.querySelector('.friend-message');
        if (!messageDiv) {
          messageDiv = document.createElement('div');
          messageDiv.classList.add('friend-message');
          friendCard.appendChild(messageDiv);
        }

        messageDiv.innerHTML = `
          <div class="last-message">${lastMessage.content}</div>
          <div class="message-time">${new Date(lastMessage.timestamp).toLocaleTimeString([], {
            hour: '2-digit',
            minute: '2-digit'
          })}</div>
        `;
      }
    }
  } catch (err) {
    console.error('获取最新消息失败:', err);
  }

  // 更新未读消息计数和气泡提示
  showMessageBubble(`收到来自 ${sender.nickname} 的新消息`);
  unreadCounts[senderId] = (unreadCounts[senderId] || 0) + 1;
  updateUnreadBadge(senderId, unreadCounts[senderId]);
});

// 添加显示消息气泡的函数
function showMessageBubble(message) {
  const bubble = document.createElement('div');
  bubble.className = 'message-bubble';
  bubble.textContent = message;
  document.body.appendChild(bubble);

  // 3秒后自动删除气泡
  setTimeout(() => {
    bubble.remove();
  }, 3000);
}

// 移动端触摸优化
document.addEventListener('DOMContentLoaded', () => {
  // 禁用双击缩放
  let lastTouchEnd = 0;
  document.addEventListener('touchend', (event) => {
    const now = Date.now();
    if (now - lastTouchEnd <= 300) {
      event.preventDefault();
    }
    lastTouchEnd = now;
  }, false);

  // 优化点击延迟
  document.addEventListener('touchstart', () => {}, {passive: true});

  // 优化滚动性能
  const container = document.querySelector('.container');
  if (container) {
    container.addEventListener('touchstart', () => {}, {passive: true});
    container.addEventListener('touchmove', () => {}, {passive: true});
  }
});
